package com.ywj.chatroom.multiroom.server.handler;

import com.ywj.chatroom.multiroom.message.GroupChatRequestMessage;
import com.ywj.chatroom.multiroom.message.GroupChatResponseMessage;
import com.ywj.chatroom.multiroom.server.session.GroupSessionFactory;
//import java.nio.channels.Channel;
import io.netty.channel.Channel;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.List;

/**
 * 群聊消息处理器
 * 1.获取群聊名字    2.获取发送的内容
 * 3.获取这个群里面所有的成员的channel   4.给除了自己以外的所有channel发送消息
 */
@ChannelHandler.Sharable
public class GroupChatRequestMessageHandler extends SimpleChannelInboundHandler<GroupChatRequestMessage> {
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, GroupChatRequestMessage msg) throws Exception {
        //内容
        String content = msg.getContent();
        //获取成员
        List<Channel> membersChannel = GroupSessionFactory.getGroupSession()
                .getMembersChannel(msg.getGroupName());
        if(membersChannel == null){
            ctx.writeAndFlush(new GroupChatResponseMessage(false, "群聊不存在"));
        }else{
            for (Channel channel : membersChannel) {
                if(!ctx.channel().equals(channel)){
                    //不给自己发消息
                    channel.writeAndFlush(new GroupChatResponseMessage(msg.getFrom(), msg.getContent()));
                }
            }
        }
    }
}



